$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'storeMember/storemember/list',
        datatype: "json",
        colModel: [
            {label: 'sid', name: 'sid', index: 'sid', width: 50, key: true, hidden: true},
            {label: '用户id', name: 'memberId', index: 'member_id', width: 80, align: 'center'},
            {label: '姓名(公司名称)', name: 'name', index: 'name', width: 130},
            {label: '门店会员类型', name: 'merchantsType', index: 'merchants_type', width: 80, align: 'center',
                formatter: function (value, options, row) {
                    if(value == 'register'){
                        return "注册"
                    }else if(value == 'visit'){
                        return "来访"
                    }else{
                        return value
                    }
                }},
            {label: '门店业务员', name: 'merchantsSalesMan', index: 'merchants_sales_man', width: 80, align: 'center'},
            {label: '创建时间', name: 'createTime', index: 'create_time', width: 80, align: 'center'},
            {label: '挂账客户', name: 'hangsAccountCustomer', index: 'hangs_account_customer', width: 50, align: 'center'},
            {label: '价格账套', name: 'priceSetName', index: 'priceSetName', width: 50, align: 'center'},
            {label: '价格账套', name: 'priceSet', index: 'price_set', width: 80, align: 'center', hidden: true},
            {label: '用户昵称', name: 'nickname', index: 'nickname', width: 80, align: 'center'},
            {label: '地址', name: 'addr', index: 'addr', width: 80, align: 'center'},
            {label: '手机', name: 'mobile', index: 'mobile', width: 80, align: 'center'},
            {label: '固定电话', name: 'tel', index: 'tel', width: 80, align: 'center'},
            {label: '预存款', name: 'advance', index: 'advance', width: 50, align: 'center'},
            { label: '操作', name: 'edit', index: 'edit', width: 30 ,align: 'center',
                formatter:function(value, options, row){
                    var actions = [];
                    actions.push('<a href="javascript:void(0);" onclick="vm.edit(' + row.memberId + ',' + row.advance + ');">充值</a>') ;
                    return actions.join(' ');
                }
            }
        ],
        viewrecords: true,
        height: window.innerHeight-125,
        rowNum: 25,
        rowList: [25, 50, 80],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount",
            userdata: "userData"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
            vm.sellernames = $("#jqGrid").jqGrid('getGridParam', 'userData').sellernames;
            //查询当前商户的全部账套信息
            $.get(baseURL + "storeFavouredPrice/storefavouredprice/getAllFavoured", function (r) {
                vm.storeFavouredPriceEntityList = r.storeFavouredPriceEntityList;
            });
        }
    });
});
var DUmsocx1;
var ws;
var flag=0;
function ToggleConnectionClicked() {
    try {
        /*
        //检测当前浏览器是否支持websocket模式
        window.WebSocket = window.WebSocket || window.MozWebSocket;
                  if (!window.WebSocket){
                              alert("WebSocket not supported by this browser");
                              return;
                  }*/
        ws = new WebSocket("ws://127.0.0.1:1818");//连接服务器

        ws.onopen = function(event){
            //alert("已经与服务器建立了连接\r\n当前连接状态："+this.readyState);
            flag=0;
            ws.send(DUmsocx1);
            //SendData(DUmsocx1);
        };
        ws.onmessage = function(event){
            vm.sweepCodeCallBack(event.data);
            //截取数字
            /*if (event.data.substring(0,2) === '00'){ // 交易成功
                //请求后台业务
                vm.sweepCodeCallBack(event.data);

            }else{
                vm.loading.close();
                alert("接收到服务器发送的数据：\r\n"+event.data);
            }*/
            flag=1;
        };
        ws.onclose = function(event){
            //alert("已经与服务器断开连接\r\n当前连接状态："+this.readyState);
        };
        ws.onerror = function(event){
            if (flag!=1)
                alert("WebSocket接收异常！");
        };
    } catch (ex) {
        alert(ex.message);
    }
};
var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        storeMember: {},
        q: {
            username: ''
        },
        storeFavouredPriceEntityList: [], //当前商户的全部账套信息
        dialogVisible:false,
        count:'', //充值数量
        advance:'', //当前预存款
        memberId:'', //用户id
        sellernames:[], //业务员集合
        payWay:'0',// 0 现金 1扫码
        serialCode: null,// 串码
        paymentId: null,// 支付ID
        loading: null,
    },
    methods: {
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.storeMember = {
                hangsAccountCustomer: 0,
                sex: 1
            };
        },
        update: function (event) {
            var sid = getSelectedRow();
            if (sid == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";

            vm.getInfo(sid)
        },
        saveOrUpdate: function (event) {
            if (!vm.storeMember.name) {
                alert('会员名不能为空!')
                return
            }
            const numReg=/^[0-9]*$/
            if (numReg.test(vm.storeMember.name)) {
                alert('会员名不能为手机号码或纯数字!')
                return
            }
           //匹配只能输入字母数字汉字
           //   const nameReg= /^[A-Za-z0-9\u4e00-\u9fa5]+$/
           //  if (!nameReg.test(vm.storeMember.name)){
           //      alert('会员名只能输入汉字、字母、非纯数字!')
           //      return
           //  }
            if (vm.storeMember.mobile&&!isPoneAvailable(vm.storeMember.mobile)) {
                alert("请检查手机号码")
                return
            }
            var url = vm.storeMember.sid == null ? "storeMember/storemember/save" : "storeMember/storemember/update";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.storeMember),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        del: function (event) {
            var sids = getSelectedRows();
            if (sids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: baseURL + "storeMember/storemember/delete",
                    contentType: "application/json",
                    data: JSON.stringify(sids),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        getInfo: function (sid) {
            $.get(baseURL + "storeMember/storemember/info/" + sid, function (r) {
                vm.storeMember = r.storeMemberVO;
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {//postData此数组内容直接赋值到url上，参数类型：{name1:value1…}
                    'username': vm.q.username.trim()
                },
                page: 1
            }).trigger("reloadGrid");
        },
        reset() {
            vm.q.username = '';
            vm.reload()
        },
        query() {
            vm.reload();
        },
        edit(memberId,advance) {
            vm.advance=advance
            vm.memberId=memberId
            vm.payWay='0'
            vm.count=''
            vm.serialCode=''
            vm.dialogVisible=true
        },
        addAdvance() {
            if (!vm.count || vm.count<=0) {
                alert('请输入有效充值金额!')
                return
            }
            $.ajax({
                type: "POST",
                url: baseURL + "storeMember/storemember/addAdvance",
                dataType: "json",
                data: {'memberId':vm.memberId,'advance':vm.count,'payWay':'现金存入'},
                success: function (r) {
                    if (r.code == 0) {
                        alert('操作成功', function (index) {
                            $("#jqGrid").trigger("reloadGrid");
                            vm.dialogVisible=false
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        //支付方式 发生改变
        changePayWay: function (value) {
            if (value === '1'){
                var self = this;
                setTimeout(function() {
                    self.$refs.serialCodeRef.focus();
                }, 500);
            }
        },
        //监听串码 change
        serialCodeChange: function (value) {
            if (isBlank(value)){
                return;
            }
            // 1.请求后台写入支付ready 流水
            // 开启加载框
            this.loading = this.$loading({
                lock: true,
                text: '扫码充值中,请勿刷新页面!',
                spinner: 'el-icon-loading',
            });
            var self = this;
            $.ajax({
                type: "POST",
                url: baseURL + "storeMember/storemember/sweepCodeBegin",
                contentType: "application/json",
                data: JSON.stringify({'memberId':vm.memberId,'advance':vm.count,'serialCode':vm.serialCode}),
                success: function(r){
                    if(r.code == 0){
                        // 2.调用银联ocx 支付
                        vm.paymentId = r.paymentId;
                        DUmsocx1 = r.DUmsocx1;
                        ToggleConnectionClicked();
                    }else{
                        // 关闭加载框
                        self.loading.close();
                        alert(r.msg);
                    }
                }
            });
        },
        //扫码支付回调
        sweepCodeCallBack :function (data) {
            var self= this;
            $.ajax({
                type: "POST",
                url: baseURL + "storeMember/storemember/sweepCodeCallBack",
                contentType: "application/json",
                data: JSON.stringify({'paymentId':vm.paymentId,'sweepCodeData':data}),
                success: function(r){
                    // 关闭加载框
                    self.loading.close();
                    if(r.code == 0){
                        // 此处关闭弹窗
                        vm.dialogVisible=false;
                        vm.paymentId = null;
                        vm.sweepCodeData = null;
                        self.$message({
                            message: '充值成功!',
                            type: 'success'
                        });
                        $("#jqGrid").trigger("reloadGrid");
                    }else{
                        alert(r.msg);
                    }
                }
            });

        },
    }
});

//手机号码正则
function isPoneAvailable(str) {
    var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    if (!myreg.test(str)) {
        return false;
    } else {
        return true;
    }
}